const http = require('../../../utils/http.js');
const tools = require('../../../utils/tools.js');

Page({
  data: {
    base_candidate_info: {
      id_number: '',
      phone: '',
      name: '',
      gender: '',
      birth_date: '',
      ethnicity_id: '',
      foreign_language_id: '',
      political_status_id: ''
    },
    genderOptions: ['男', '女'],
    genderIndex: null,
    ethnicityOptions: [],
    ethnicityIndex: null,
    politicalStatusOptions: [],
    politicalStatusIndex: null,
    foreignLanguageOptions: [],
    foreignLanguageIndex: null,
    // 语音相关数据
    recognitionResult: '',
    recordedText: null,
    recording: false,   // 正在录音标志
    isPaused: false,
    recordFilePath: '', // 录音文件临时路径
    editableContent: '', // 语音识别后文本内容
    buttonText: '开始录音', // 录音按钮文本
    // 下一页的url
    nextUrl:''
  },

  /**
   * 页面加载生命周期函数
   * 加载下拉框选项，并初始化页面
   */
  onLoad(query) {
    // 加载上个页面传入的数据
    this.setData({nextUrl:query.nextUrl});
    // 加载下拉框选项数据
    const ethnicityPromise = tools.fetchOptions('/ethnicity/list', 'ethnicityOptions', this);
    const politicalStatusPromise = tools.fetchOptions('/politicalstatus/list', 'politicalStatusOptions', this);
    const foreignLanguagePromise = tools.fetchOptions('/foreignlanguage/list', 'foreignLanguageOptions', this);
  
    // 等待选项加载完成后，再加载本地预填数据
    Promise.all([ethnicityPromise, politicalStatusPromise, foreignLanguagePromise]).then(() => {
      const storedInfo = wx.getStorageSync('base_candidate_info');
      if (storedInfo) {
        storedInfo.birth_date = tools.formatDate(storedInfo.birth_date);
        this.setData({
          base_candidate_info: storedInfo
        });
        this.updateIndex(storedInfo);
      } else {
        wx.showToast({ title: '请先登录或注册', icon:"error", duration:3000 });
        wx.switchTab({
          url: '/pages/registration/registration',
        })
      }
    }).catch(err => {
      console.error('加载选项数据失败:', err);
    });
  },

  /**
   * 根据预存信息更新各下拉框选项索引
   * @param {Object} storedInfo - 本地存储的基本信息对象
   */
  updateIndex(storedInfo) {
    this.setData({
      genderIndex: this.data.genderOptions.indexOf(storedInfo.gender),
      ethnicityIndex: tools.findIndexById(this.data.ethnicityOptions, storedInfo.ethnicity_id),
      politicalStatusIndex: tools.findIndexById(this.data.politicalStatusOptions, storedInfo.political_status_id),
      foreignLanguageIndex: tools.findIndexById(this.data.foreignLanguageOptions, storedInfo.foreign_language_id),
    });
  },

  /**
   * 日期选择回调函数
   * @param {Object} e - 事件对象
   */
  handleDateChange(e) {
    this.setData({
      'base_candidate_info.birth_date': e.detail.value
    });
  },

  /**
   * 下拉框选择回调函数
   * 这里只更新下标，实际提交时根据下标获取对应选项的 id
   * @param {Object} e - 事件对象
   */
  handlePickerChange(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({
      [`${field}Index`]: e.detail.value
    });
  },

  /**
   * 输入框回调函数
   * @param {Object} e - 事件对象
   */
  handleInput(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({
      [`base_candidate_info.${field}`]: e.detail.value
    });
  },

  /**
   * 提交表单并跳转到下一页（学籍基础信息填写页面）
   * 验证必填字段并提交数据
   */
  handleSubmit() {
    const errors = tools.validateCandidateInfo(this.data.base_candidate_info)
    // === 错误提示 ===
    if (errors.length > 0) {
      wx.showToast({
        title: errors[0],
        icon: "none",
        duration: 2000,
      });
      return;
    }
    
    // 构建待提交的对象：根据下拉框的 index 获取对应 id 值
    const current_base_candidate_info = {
      id_number: this.data.base_candidate_info.id_number,
      phone: this.data.base_candidate_info.phone,
      name: this.data.base_candidate_info.name,
      gender: this.data.genderOptions[this.data.genderIndex] || '',
      birth_date: this.data.base_candidate_info.birth_date,
      ethnicity_id: this.data.ethnicityOptions[this.data.ethnicityIndex].id,
      foreign_language_id: this.data.foreignLanguageOptions[this.data.foreignLanguageIndex].id,
      political_status_id: this.data.politicalStatusOptions[this.data.politicalStatusIndex].id
    };
    console.log(current_base_candidate_info);
    const storedInfo = wx.getStorageSync('base_candidate_info');
    const fieldsToCheck = [
      'id_number', 'phone', 'name', 'gender', 'birth_date', 
      'ethnicity_id', 'foreign_language_id', 'political_status_id'
    ];

    if(tools.checkDataChanged(current_base_candidate_info,storedInfo,fieldsToCheck)){
      // 调用后端接口更新基本信息（接口地址可按实际情况调整）
      http.post("/candidate/updateBasicInfo", current_base_candidate_info).then(res => {
      console.log(res);
      if (res.data.code === 200) {
        wx.setStorageSync('base_candidate_info', current_base_candidate_info);
        wx.showToast({ title: '基本信息更新成功', duration: 2000 });
        // 跳转到学籍基础信息填写页面
        wx.navigateTo({ url: this.data.nextUrl });
      }
      }).catch(err => {
      console.log(err);
      wx.showToast({ title: '基本信息更新失败', duration: 2000 });
      });
    }else{
      // 跳转到学籍基础信息填写页面
      wx.navigateTo({ url: this.data.nextUrl });
    }
    
  },

    // 语音功能
    // 录音功能区
  /**
   * 切换录音状态（开始/停止录音）
   */
  toggleRecording() {
    if (this.data.recording) {
      this.setData({ recording: false });
      const recorderManager = wx.getRecorderManager();
      recorderManager.stop();
      recorderManager.onStop((res) => {
        wx.setStorageSync('recordPath', res.tempFilePath);
        this.setData({ recordFilePath: res.tempFilePath });
        this.setData({ buttonText: '开始录音' });
      });
    } else {
      tools.checkRecordPermission().then(()=>{
        this.setData({ recording: true, buttonText: '停止录音' });
        // 开始录音
        const recorderManager = wx.getRecorderManager();
        recorderManager.start({
          format: 'wav',
          duration: 60000,
          sampleRate: 44100,
          numberOfChannels: 1,
          encodeBitRate: 96000
        });
      })
      .catch(() => {
        wx.showToast({ title: err.message, icon: 'none' });
      });
    }
  },

  /**
   * 上传录音文件并进行语音识别
   */
  uploadAndRecognizeRecording() {
    if (!this.data.recordFilePath) {
      wx.showToast({ title: '请先录制录音', icon: 'none' });
      return;
    }
    const filePath = this.data.recordFilePath;
    http.asr(filePath).then(res =>{
      console.log("语音识别成功，文本如下：")
      console.log(res);
      // 根据返回的文本信息，提取其中的信息
      this.setData({ editableContent: res });
      // 调用后端的识别接口
      const postData = { "text": res };
      http.zsbExtract(postData).then(res =>{
        // 处理提取后的结果
        console.log("提取后的结果，如下：")
        console.log(res)
        // this.updateIdAndIndex(res.data.data)
        this.updateIdAndIndex(res.data)
      }).catch(err => {
        // 提取失败
        console.log('无法解析识别结果：', err);
        console.log('接收到的原始返回数据：', err.data);
      });
    }).catch(err =>{
      // 语音识别失败
      console.log('语音识别失败：', err);
      wx.showToast({ title: '录音识别失败', icon: 'none', duration: 2000 });
    })
  },

  /**
   * 更新ID和索引（根据语音识别结果）
   * @param {Object} dataFields - 识别结果数据
   */
  updateIdAndIndex(dataFields){
    const fields = ["name", "gender", "birth_date", "phone", "password"]
    const idFields={
        ethnicity: 'ethnicity_id',
        political_status: 'political_status_id',
        foreign_language: 'foreign_language_id'
    }
    const arrayFields = {
        ethnicity: 'ethnicityOptions',
        political_status: 'politicalStatusOptions',
        foreign_language: 'foreignLanguageOptions'
    }
    // 根据结果给字段赋值
    fields.forEach(key =>{
        if(!dataFields[key].includes("未知")){
            this.setData({
                [`base_candidate_info.${key}`]:dataFields[key]
            })
        }
    })
    // 根据名字赋值id
    Object.entries(idFields).forEach(([key,value]) =>{
        // 通过两个字典的映射获取对应的值，查询id随后进行赋值
        if(!dataFields[key].includes("未知")){
            this.setData({
                [`base_candidate_info.${value}`]: tools.findIdByName(this.data[arrayFields[key]],dataFields[key])
            })
        }
    })
    //更新下标
    this.updateIndex(this.data.base_candidate_info)
  },

});
